﻿app.controller('NewItemController', ['$scope', '$location', 'GroceryService', function ($scope, $location, GroceryService) {
    $scope.item = {};

    $scope.isLoading = function () {
        $scope.buttonText = $scope.loading ? 'Please Wait...' : 'Add Item';
        return $scope.loading;
    };

    $scope.addItem = function () {
        $scope.loading = !$scope.loading;
        $scope.item.typeId = $scope.selectedType.value;
        return GroceryService.addItem($scope.item)
            .then(function () {
                $scope.loading = !$scope.loading;
                $location.path('/groceries');
            }, function (data) {
                $scope.errorMessage = data.error_description;
                $scope.loading = !$scope.loading;
            });
    };

    $scope.loading = !$scope.loading;
    return GroceryService.getGroceryItemTypes().then(function (data) {
        $scope.loading = !$scope.loading;
        $scope.itemTypes = data;
    });
}]);